package mis

import (
	"encoding/json"
	"strings"

	"github.com/gin-gonic/gin"

	"gin-api-server/app/model/db"
	"gin-api-server/core_library/global"
	"gin-api-server/core_library/library/webengine/resp"
	"gin-api-server/utils/common"
)

type GetDbConfigDataRequest struct {
	Names string `json:"names" form:"names"` // 配置名称多个使用逗号隔开
}

type GetDbConfigDataResponse struct {
	Name  string `json:"name"`  // 配置名称
	Value any    `json:"value"` // 配置值 返回值根据配置类型不同而不同
}

// GetDbConfigDataServer
// @Summary 获取数据库配置
// @Tags  Mis
// @Accept  json
// @Produce json
// @Param names query string true "配置名称多个使用逗号隔开"
// @Router /mis/dbconfig [get]
// @Success 200 {object}  GetDbConfigDataResponse
func GetDbConfigDataServer(c *gin.Context) {
	var reqBody GetDbConfigDataRequest
	if err := c.ShouldBindQuery(&reqBody); err != nil {
		resp.FailWithMessage(c, "参数错误: "+err.Error())
		return
	}
	var data []db.Config
	global.DB.Where("name in (?)", strings.Split(reqBody.Names, ",")).Find(&data)
	var result = make(map[string]GetDbConfigDataResponse, len(data))
	for _, v := range data {
		var value any
		switch v.Type {
		case "array":
			_ = json.Unmarshal([]byte(v.Value), &value)
		case "image":
			value = common.CdnUrl(v.Value)
		case "images":
			images := strings.Split(v.Value, ",")
			for i, v := range images {
				images[i] = common.CdnUrl(v)
			}
			value = images
		default:
			value = v.Value
		}
		result[v.Name] = GetDbConfigDataResponse{
			Name:  v.Name,
			Value: value,
		}
	}
	resp.OkWithData(c, result)

}
